<?php

namespace app\common\validate;

use think\Config;
use think\Validate;

class BaseValidate extends Validate
{
    // 添加全局验证方法
    protected function ids($value, $rule, $data = [])
    {
        $ids = explode(',', $value);
        foreach ($ids as $id) {
            if (!is_numeric($id) || $id < 1) {
                return false;
            }
        }
        return true;
    }

    /**
     * 校验decimal(a,b)类型长度  a:精度,b:标度
     * @param $value
     * @param array|string $rule [6,4] or '6,4'
     * @param $data
     * @return bool
     */
    protected function decimal($value, $rule, $data = [])
    {
        if (is_string($rule)) {
            $rule = explode(',', $rule);
        }
        $accuracy = !empty($rule[0]) ? intval($rule[0]) : 10;
        $scale = !empty($rule[1]) ? intval($rule[1]) : 4;
        if (Config::get('APP_DEBUG')) {
            self::setTypeMsg([
                'decimal' => ":attribute must decimal($accuracy,$scale)",
            ]);
        }
        $length = [$accuracy - $scale, $scale];
        $decimal_regular = "/^\-?\d{1,$length[0]}(\.\d{1,$length[1]})?$/";
        if (is_array($value)) {
            foreach ($value as $item) {
                if (!preg_match($decimal_regular, $item)) {
                    return false;
                }
            }
        } else {
            if (!preg_match($decimal_regular, $value)) {
                return false;
            }
        }
        return true;
    }
}